//
//  RSComposeViewController.swift
//  RSWeibo
//
//  Created by Macx on 16/8/17.
//  Copyright © 2016年 Macx. All rights reserved.
//

import UIKit
import SVProgressHUD

class RSComposeViewController: UIViewController {
    
    
    // 懒加载 控件
    // 右侧的按钮
    private lazy var rightButton: UIButton = {
    
        let btn = UIButton()
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        // 不同状态的文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        // 设置不同状态的背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        //  设置大小
        btn.frame.size = CGSizeMake(45, 30)
        // 添加点击方法
        btn.addTarget(self, action: "sendBtnAction", forControlEvents: .TouchUpInside)
        
        // 默认状态下是不可用的
//        btn.enabled = true
        
        return btn
    }()
    
    // 自定义的标题视图
    private lazy var titleLab: UILabel = {
    
        let lab = UILabel(fontSize: 15, textColor: UIColor.blackColor())
        
        // 从模型中取出当前登录的账户的名称, 判断能否赋值成功
        if let name = RSUserAccoutViewModel.sharedUserAccountViewModel.userAccountModel?.name {
        
            let titleName = "发微博\n\(name)"
            
            // 把titleName转换成可变特性的字符串
            let attribStr = NSMutableAttributedString(string: titleName)
            
            // 从titleName中找到要改变特性的字符串, 也就是name那部分
            let range = (titleName as NSString).rangeOfString(name)
            
            // 添加副文本属性
            attribStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)], range: range)
            lab.text = titleName
        }else{
        
            lab.text = "发送微博"
        }
        
        
        // 换行
        lab.numberOfLines = 0
        lab.sizeToFit()
        lab.textAlignment = .Center
        
        
        return lab
    }()
    
    
    // toolbar
    private lazy var toolbar: RSComposeToolBarStackView = {
        
        let toolbar = RSComposeToolBarStackView(frame: CGRectZero)
        // 本身没有渲染效果, 得手动添加
        toolbar.backgroundColor = UIColor.yellowColor()
        return toolbar
        
        }()
    
    // 输入视图
    private lazy var textView: RSComposeTextView = {
    
        let textView = RSComposeTextView()
        textView.backgroundColor = UIColor.whiteColor()
        
        // 关掉自动输入纠错功能
        textView.autocorrectionType = .No
        
        return textView
    }()
    
    // 图片框
    private lazy var picturesView: RSComposePictrueView = {
        
        let picView = RSComposePictrueView()
        return picView
    }()
    
    // 表情键盘的懒加载
    private lazy var emotionKeyboard: RSEmotionKeyboardView = {
    
        let emotionKeyboard = RSEmotionKeyboardView()
        // 设置大小
        emotionKeyboard.frame.size = CGSize(width: self.textView.frame.size.width,height: 216)
        emotionKeyboard.backgroundColor = UIColor.whiteColor()
        return emotionKeyboard
    }()
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    
    private func setupUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        picturesView.backgroundColor = view.backgroundColor
        
        // 设置键盘弹出的和收回的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
        
        // 设导航栏的布局
        setupNavUI()
        
        
        // 添加控件
        view.addSubview(toolbar)
        
        // 添加
        view.addSubview(textView)
        textView.addSubview(picturesView)
        
        // 设置 textView 的代理
        textView.delegate = self
        
        // 设置约束
        toolbar.snp_makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(40)
        }
        
        textView.snp_makeConstraints { (make) in
            make.top.equalTo(view).offset(64)
            make.leading.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(toolbar.snp_top)
        }
        picturesView.snp_makeConstraints { (make) in
            make.top.equalTo(textView.snp_top).offset(120)
            make.centerX.equalTo(textView.snp_centerX)
            make.width.equalTo(textView.snp_width).offset(-10)
            make.height.equalTo(textView.snp_width).offset(-10)
        }
        
        // 在这里定义toolbar中的闭包属性, 相当于在这里执行. 这里有循环引用
        toolbar.didselectedToolBarButtonClosure = { [weak self] (type: RSComposeBarButtonType) in
            
//            print(self)
            switch type {
            case .picture:
                self!.didSelectedPicBtn()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
//                print("表情")
                self!.didselectedEmotionKeyboard()
            case .add:
                print("添加")
            
            }
        
        }
        
        // 定义 点击加号cell调用选择图片的闭包, 这里也会形成循环引用
        picturesView.pickerImageClosure = { [weak self] in

            // 调用选择图片的方法
            self!.didSelectedPicBtn()
        }
        
    }
    
    // 点击表情键盘的时候弹出表情键盘
    private func didselectedEmotionKeyboard(){
        
        // 如果是系统键盘, 就切换成表情键盘, 
        if textView.inputView == nil {
            // 切换成表情键盘
            textView.inputView = emotionKeyboard
            // 更改图标为表情键盘的
            toolbar.swithToEmotionButton(true)
            
        }else {
         
            // 如果是表情键盘, 就切换成系统键盘
            textView.inputView = nil
            // 更改图标为键盘键盘的
            toolbar.swithToEmotionButton(false)
        }
        // 让输入框成为第一响应者
        textView.becomeFirstResponder()
        // 刷新inputview, 否则的话是切换不了键盘的
        textView.reloadInputViews()
    }
    
    // 设置导航栏的视图
    private func setupNavUI(){
    
        // 创建左侧的 取消按钮
        let leftBtn = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancelAction")
        // 赋值给导航栏左侧按钮属性
        navigationItem.leftBarButtonItem = leftBtn
        
        // 设置右侧的按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置标题按钮
        navigationItem.titleView = titleLab
        
    }
    
    // 点击 取消 按钮返回主页面
    @objc private func cancelAction(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}


extension RSComposeViewController{
    
    // 点击 发送 按钮
    @objc private func sendBtnAction(){
        
        // 判断有没有图片,有的话就调用发送图片和文字的按钮
        if picturesView.picArr.count > 0{
        
            // 获取文本输入框中的内容
            let status = textView.text
            // 获取图片
            let img = picturesView.picArr[0]
            RSNetTool.sharedTool.sendstatusAndimages((RSUserAccoutViewModel.sharedUserAccountViewModel.userAccountModel?.access_token)!, status: status, image: img, callBack: { (reseponse, error) in
                
                if reseponse != nil {
                    
                    print("发送微博成功")
                } else if error != nil{
                    
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                }
            })
        }
        
        // 获取文本输入框中的内容
        let status = textView.text
//        print(status)
        
        // 调用网络工具, 想服务器发送
        RSNetTool.sharedTool.sendStatuses((RSUserAccoutViewModel.sharedUserAccountViewModel.userAccountModel?.access_token)!, status: status) { (reseponse, error) in
            if reseponse != nil {
            
                print("发送微博成功")
            } else if error != nil{
            
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
            }
        }
        // 弹出提示框
        SVProgressHUD.showSuccessWithStatus("发送成功")
        
        // 延迟半秒后返回到主界面
//        NSThread.sleepForTimeInterval(5)
        
        // 点击发送后, 要弹回到主页面
//        dismissViewControllerAnimated(true, completion: nil)
    }


    
}



// 点击toolbar按钮的处理逻辑
extension RSComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    // 点击图片按钮调用的方法
    private func didSelectedPicBtn(){
    
        // 创建一个图片拾取器
        let picCtr = UIImagePickerController()
        
        // 设置拾取器的代理
        picCtr.delegate = self
        
        // 判断能不能响应相机, 能的话进入相机, 不能的话进入相册
        // 判断相机能不能用
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
        
            // 相机可以用, 就把数据来源设为相机
            picCtr.sourceType = .Camera
        }else{
        
            // 如果相机不能打开, 就把数据来源设为相册
            picCtr.sourceType = .PhotoLibrary
        }
        
        // 是否允许编辑相片
//        picCtr.allowsEditing = true
        
        // 判断是不是前置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Front){
        
            print("前置摄像头可用")
        }else if UIImagePickerController.isCameraDeviceAvailable(.Rear){
        
            print("后置摄像头可用")
        }else{
        
            print("前后摄像头都不可用")
        }
        
        // 弹出拾取器
        presentViewController(picCtr, animated: true, completion: nil)
        
        
    }
    
    // 点击
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print("见到图pan")
        
        // 选择图片后, 调用方法将其进行等比压缩, 然后再添加到数组中
        let scaleImage = image.scaleImageWithWidth(200)
        
        // 调用方法, 把图片添加到图片数组中
        picturesView.appendToPicArr(scaleImage)
        
        // 弹回选择视图
        dismissViewControllerAnimated(true, completion: nil)
    }

}




/*
 
 UITextViewDelegate 是继承自 uiscrollViewDelegate 的, 可以有滚动的代理方法
 */

// MARK:  textview 的代理方法

extension RSComposeViewController: UITextViewDelegate{

     func textViewDidChange(textView: UITextView) {
        
        // 当textView有内容的时候, 右侧发送按钮可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    // 当 textview 准备拖动的时候
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
//        print("准备拖动了")
        
       // 拖动的时候, 让textView失去第一响应者地位
        textView.endEditing(true)
    }
}


// 监听键盘frame改变的通知
extension RSComposeViewController{

    @objc private func keyboardFrameChange(notificator: NSNotification){
        
        // 获取到键盘的 frame
        let keyboardFrame = (notificator.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()

        toolbar.snp_remakeConstraints { (make) in
            
            // 修改键盘的约束
            //                make.bottom.equalTo(view).offset(-271)
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - self.view.frame.size.height)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(40)
        }
  
        
        // 这种方法有bug
//        if keyboardFrame.origin.y == 465 {
//        
//            
//            toolbar.snp_remakeConstraints { (make) in
////                make.bottom.equalTo(view).offset(-271)
//                make.bottom.equalTo(view).offset(keyboardFrame.origin.y - self.view.frame.size.height)
//                make.leading.equalTo(view)
//                make.trailing.equalTo(view)
//                make.height.equalTo(40)
//            }
//            
//        }else if keyboardFrame.origin.y == 736{
//        
//            toolbar.snp_remakeConstraints { (make) in
//                make.bottom.equalTo(view).offset(0)
//                make.leading.equalTo(view)
//                make.trailing.equalTo(view)
//                make.height.equalTo(40)
//            }
//            
//          }
        
    }
}




















